<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="视频名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入视频名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-select v-model="queryParams.enable" placeholder="请选择状态" clearable style="width: 240px" >
            <el-option label="显示" :value="1" />
            <el-option label="隐藏" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            placeholder="请选择日期"
            v-model="queryParams.scene"
            style="width: 240px"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:dict:add']"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="视频名称" align="center" prop="taskName" :show-overflow-tooltip="true" />
        <el-table-column label="视频" align="center" prop="status">
          <template slot-scope="scope">
            <div>
                <video :src="scope.row.taskUrl" controls width="100px" style="width: 100px;max-height:200px"></video>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="日期" align="center" prop="enable" width="180">
          <template slot-scope="scope">
            <el-tag>{{scope.row.enable?'显示':'隐藏'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="日期" align="center" prop="taskScene" width="180" />
        <el-table-column label="创建日期" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dict:edit']">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="视频名称" prop="taskName">
            <el-input v-model="form.taskName" placeholder="请输入视频名称" />
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="form.taskScene" type="date" @change="changeReleaseTime" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="视频" prop="taskUrl">
            <el-upload class="avatar-uploader" :action="uploadImgUrl" :show-file-list="false" :on-success="handleVideoSuccess"
                :before-upload="beforeVideoUpload" name="file" :headers="{saasToken: saasToken, Develop: 'prod'}" :http-request="handleRequest" :with-credentials="true">
                <video v-if="form.taskUrl" :src="form.taskUrl" controls="controls" class="video-box" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <el-progress v-if="showProgress" :percentage="progressPercent" :status="progressStatus"></el-progress>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否显示" prop="enable">
            <el-radio-group v-model="form.enable">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="0">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { taskSave, taskList, taskUpdate } from "@/api/advert/advert";
  import { uploadFile } from "@/api/uploadFile";
  import md5 from 'js-md5';
  import dayjs from 'dayjs'
  
  export default {
    name: "advert",
    data() {
      return {
        uploadImgUrl: process.env.VUE_APP_UPLOAD_API + "/file/uploadFile",
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
            taskName: [
                { required: true, message: "视频名称不能为空", trigger: "blur" }
            ],
            taskUrl: [
                { required: true, message: "视频不能为空", trigger: "change" }
            ],
            enable: [
                { required: true, message: "是否显示不能为空", trigger: "change" }
            ]
        },
        progressPercent: 0,
        progressStatus: null,
        showProgress: false,
        saasToken: ''
      };
    },
    created() {
        let date = dayjs().format('YYYYMMDD')
        let saasToken = date + 'MNAc1qMEyQXauIVckovoh5gklhQnziyZ' + 2
        this.saasToken = md5(saasToken)
        this.getList();
    },
    methods: {
        /** 查询字典类型列表 */
        getList() {
            this.loading = true;
            taskList(this.queryParams).then(res => {
                this.typeList = res.data;
                this.total = res.extend.total;
                this.loading = false;
            });
        },
        changeReleaseTime() {

        },
        handleVideoSuccess(res, file) {

        },
        beforeVideoUpload(file) {
            if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
                this.$message.error('请上传正确的视频格式');
                return
            }
            const isLt2M = file.size / 1024 / 1024 < 200;
            if (!isLt2M) {
                this.$message.error('上传视频大小不能超过 200M!');
                return
            }
        },
        async handleRequest(data) {
            let formdata = new FormData();
            formdata.append('file', data.file);
            formdata.append('platform', 6);
            this.showProgress = true
            this.progressStatus = null;
            const config = {
                onUploadProgress: event => {
                    // event.loaded:已上传文件大小
                    // event.total:被上传文件的总大小
                    this.progressPercent = Number((event.loaded / event.total * 100) | 0) > 98 ? 98 : Number((event.loaded / event.total * 100) | 0);
                    console.log("progressPercent1", this.progressPercent)
                }
            };
            let uploadRes = await uploadFile(formdata, config);
            console.log('uploadRes',uploadRes);
            if (uploadRes.code == 200) {
                this.progressPercent = 0;
                this.showProgress = false
                this.progressStatus = 'success';
                this.$set(this.form, 'taskUrl', uploadRes && uploadRes.data)
                this.$message({
                    type: 'success',
                    message: "上传成功",
                });
            } else {
                this.progressPercent = 0;
                this.showProgress = false
                this.$message({
                    type: 'error',
                    message: "上传失败",
                });
            }
        },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          dictId: undefined,
          dictName: undefined,
          dictType: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加广告";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.dictId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.form = row;
        this.open = true;
        this.title = "修改广告";
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.taskType = 'video'
            if(!this.form.taskScene){
              this.form.taskScene = 'commonDate'
            }
            if (this.form.id) {
                taskUpdate(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
                taskSave(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
    }
  };
</script>

<style lang="scss" scoped>

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.video-box {
    width: 100%;
    max-height: 400px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

::v-deep .el-dialog__body{
    padding: 20px 40px;
    box-sizing: border-box;
}

</style>